package com.youran.restful.webprinter.ctrl;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.youran.restful.webprinter.model.FileInfo;
import com.youran.restful.webprinter.service.FileOperater;

/**
 * 打印请求处理中心
 * 
 * @author feng
 */
@RestController
@RequestMapping("/webprint")
public class PrintCtrl extends CommonCtrl {

	private Logger logger = LoggerFactory.getLogger(PrintCtrl.class);
	
	@Autowired
	private FileOperater fileOp;

	/**
	 * 网络打印服务首页
	 * @return
	 */
	@RequestMapping(value = { "/", "" }, method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView index() {
		logger.info("欢迎访问网络打印服务……");
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("sessionId", getGenId());
		return mav;
	}

	/**
	 * 异步上传文档
	 * @param file 二进制上传的文档内容
	 * @param sessionId 基于机器ip的操作id
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file, String sessionId) {
		logger.info("文件开始上传:{}", file.getOriginalFilename());
		
		String basePath = StringUtils.isBlank(sessionId) ? getDefaultStorePath() : getStorePath(sessionId);
		
		try {
			fileOp.uploadFile(basePath, file.getOriginalFilename(), file.getInputStream());
			
		} catch (IOException e) {
			logger.error("文件上传异常：{}", e);
		}
		
		return "success";
	}
	
	/**
	 * 跳转到待打印文件列表页面
	 * @param id 基于ip的操作id
	 * @return
	 */
	@RequestMapping(value = { "/print/{id}"}, method = { RequestMethod.GET})
	public ModelAndView goPrint(@PathVariable String id) {
		logger.info("跳转到待打印文件列表页面，sessionId={}", id);
		String basePath = getStorePath(id);
		List<FileInfo> result = fileOp.findExistFilesById(basePath);
		
		ModelAndView mav = new ModelAndView("print");
		mav.addObject("sessionId", id);
		mav.addObject("docs", result);
		logger.info("待打印的文件信息，id/列表={}/{}", id, result);
		
		return mav;
	}
	
	/**
	 * 从打印列表页面回退到上传页面
	 * @param id 基于ip的操作id
	 * @return
	 */
	@RequestMapping(value = { "/backtoupload/{id}"}, method = { RequestMethod.GET})
	public ModelAndView backToIndex(@PathVariable String id) {
		logger.info("从打印列表页面回退到上传页面，sessionId={}", id);
		
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("sessionId", id);
		mav.addObject("message", "刚才上传的文档已保存在待打印列表中");
		
		return mav;
	}
	
	/**
	 * 删除某个ip对应的目录及文档
	 * @param id 基于ip的操作id
	 * @return
	 */
	@RequestMapping(value = "/clear/{id}", method = RequestMethod.GET)
	public ModelAndView clear(@PathVariable String id) {
		if(StringUtils.isBlank(id)) {
			logger.info("sessionId为空，删除ip对应的目录");
		}
		
		String path = getStorePath(id);
		logger.info("批量删除文档，基础目录为： {}", path);
		
		String message = null;
		try {
			message = fileOp.deleteBasePath(path);
			
		} catch (Exception e) {
			logger.error("文件删除操作异常, exception:{}", e);
		}
		
		ModelAndView mav = new ModelAndView("print");
		mav.addObject("message", message);
		mav.addObject("sessionId", id);
		
		return mav;
	}
	
	/**
	 * 删除单个文档
	 * @param id 基于ip的操作id，对应服务端的一个目录
	 * @param filename 要删除的文档名称
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}/{filename}", method = RequestMethod.GET)
	public ModelAndView delete(@PathVariable String id, @PathVariable String filename) {
		logger.info("删除文档，sessionid/文件名={}/{}", id, filename);
		String basePath = getStorePath(id);
		String filepath = basePath + filename;
		
		fileOp.delete(filepath);
		
		List<FileInfo> result = fileOp.findExistFilesById(basePath);
		
		ModelAndView mav = new ModelAndView("print");
		mav.addObject("message", null);
		mav.addObject("sessionId", id);
		mav.addObject("docs", result);
		return mav;
	}
	
}
